package zyc.dao.imple;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import zyc.utils.JdbcUtils;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

/**
 * @description:
 * @author: Code-zyc
 * @date: Created in 2020/12/21 9:53
 * @version: v1.0
 * @modified By:
 */
public class BaseDao {
    private QueryRunner queryRunner = new QueryRunner();




    /**
     * @descript : 查询单列数据
     * @author :ZhaoYicong
     * @date :2020/12/21 12:59
     * @Param: type  class类 sql  sql语句  args  为占位符准备
     * @return :
     * @throws :
     * @since :
     */
    
    public <T> T selectForOne(Class<T> type,String sql,Object ...args){
        Connection connection = JdbcUtils.getconnection();
        try {
            return queryRunner.query(connection, sql, new BeanHandler<>(type), args);
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JdbcUtils.closeconnection(connection);
        }
        return null;
    }

    /**
     * @descript :查询多列数据
     * @author :ZhaoYicong
     * @date :2020/12/21 13:09
     * @Param:
     * @return :
     * @throws :
     * @since :
     */

    public <T> List<T> selectForMore(Class<T> type,String sql,Object...args){
        Connection connection = JdbcUtils.getconnection();
        try {
           return queryRunner.query(connection,sql, new BeanListHandler<>(type),args);

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {

            JdbcUtils.closeconnection(connection);
        }
        return null;
    }

    /**
     * @descript :表单的删除，修改 ，添加
     * @author :ZhaoYicong
     * @date :2020/12/21 13:16
     * @Param:
     * @return : -1 代表数据更新失败
     * @throws :
     * @since :
     */
    public int update(String sql,Object...args){
        Connection connection = JdbcUtils.getconnection();
        try {
            return queryRunner.update(connection,sql,args);

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JdbcUtils.closeconnection(connection);
        }
        return -1;

    }

    /**
     * @descript : 查询单个数据
     * @author :ZhaoYicong
     * @date :2020/12/22 14:50
     * @Param: null
     * @return :
     * @throws :
     * @since :
     */

    public   Object selectSingleValue( String sql,Object ...args){
        Connection connection = JdbcUtils.getconnection();
        try {
             return  queryRunner.query(connection,sql,new ScalarHandler(),args);
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            JdbcUtils.closeconnection(connection);
        }
        return  null;

    }



}
